document.addEventListener("DOMContentLoaded", function () {
    const settingsToggle = document.getElementById("settings-toggle");
    const settingsContent = document.getElementById("settings-content");
    const addressSelect = document.getElementById("address");
    const modelSelect = document.getElementById("model");
    const temperatureInput = document.getElementById("temperature");
    const temperatureValue = document.getElementById("temperature-value");
    const newChatButton = document.getElementById("new-chat");
    const historyList = document.getElementById("history-list");
    const chatWindow = document.getElementById("chat-window");
    const userInput = document.getElementById("user-input");

    const ADDRESSES = {
        "Ollama": {
            "base_url": "http://localhost:11434/v1",
            "models": ["glm4", "qwen2.5:3b", "llama3.2", "phi", "phi3", "deepseek-r1:1.5b", "mistral:7b-instruct-q2_k"]
        },
        "LMstudio": {
            "base_url": "http://localhost:12345/v1",
            "models": ["qwen2.5-instructv2-7b", "qwen-chatv2-7b", "deepseek-r1-qwen-7b"]
        },
        "AiGitee": {
            "base_url": "https://ai.gitee.com/api/v1",
            "models": [
                "Qwen2-7B-Instruct", "Qwen2.5-72B-Instruct", "Qwen2.5-14B-Instruct", "Qwen2.5-7B-Instruct",
                "Qwen2-72B-Instruct", "Qwen2-7B-Instruct", "Qwen2-32B-Instruct", "QwQ-32B-Preview", "Yi-34B-Chat", "glm-4-9b-chat"
            ]
        },
        "ChatGLM": {
            "base_url": "https://open.bigmodel.cn/api/paas/v4",
            "models": ["glm-4-flash"]
        },
        "THUds": {
            "base_url": "https://madmodel.cs.tsinghua.edu.cn/v1",
            "models": ["DeepSeek-R1-Distill-32B", "DeepSeek-R1-671B"]
        }
    };

    let currentConversation = [];
    let currentConversationTitle = null;
    let chatHistory = [];

    // 初始化设置
    settingsToggle.addEventListener("click", () => {
        settingsContent.classList.toggle("hidden");
    });

    addressSelect.addEventListener("change", () => {
        const selectedAddress = addressSelect.value;
        const models = ADDRESSES[selectedAddress].models;
        modelSelect.innerHTML = models.map(model => `<option value="${model}">${model}</option>`).join("");
    });

    temperatureInput.addEventListener("input", () => {
        temperatureValue.textContent = temperatureInput.value;
    });

    // 初始化模型列表
    addressSelect.dispatchEvent(new Event("change"));

    // 新建会话
    newChatButton.addEventListener("click", () => {
        if (currentConversationTitle) {
            saveConversation(currentConversationTitle, currentConversation);
        }
        currentConversationTitle = null;
        currentConversation = [];
        chatHistory = [];
        renderChatWindow();
        alert("已新建会话！");
    });

    // 加载历史记录
    function loadConversations() {
        const history = JSON.parse(localStorage.getItem("chatHistory") || [];
        historyList.innerHTML = history.map(conv => `<li>${conv.title} - ${conv.time}</li>`).join("");
    }

    // 保存对话
    function saveConversation(title, messages) {
        const history = JSON.parse(localStorage.getItem("chatHistory") || [];
        history.push({ title, time: new Date().toLocaleString(), messages });
        localStorage.setItem("chatHistory", JSON.stringify(history));
        loadConversations();
    }

    // 渲染聊天窗口
    function renderChatWindow() {
        chatWindow.innerHTML = chatHistory.map(msg => `<div class="message ${msg.role}">${msg.content}</div>`).join("");
    }

    // 用户输入
    userInput.addEventListener("keypress", async (e) => {
        if (e.key === "Enter") {
            const userMessage = userInput.value;
            if (!currentConversationTitle) {
                currentConversationTitle = userMessage.substring(0, 10);
                currentConversation = [{ role: "system", content: "这是一个多模型聊天应用，负责搞笑和幽默。" }];
            }

            currentConversation.push({ role: "user", content: userMessage });
            chatHistory.push({ role: "user", content: userMessage });
            renderChatWindow();

            const payload = {
                model: modelSelect.value,
                messages: currentConversation,
                stream: true,
                temperature: parseFloat(temperatureInput.value)
            };

            const headers = {
                "Authorization": `Bearer ${document.getElementById("api-key").value}`,
                "Content-Type": "application/json"
            };

            try {
                const response = await fetch(`${ADDRESSES[addressSelect.value].base_url}/chat/completions`, {
                    method: "POST",
                    headers: headers,
                    body: JSON.stringify(payload)
                });

                if (!response.ok) {
                    throw new Error(`API 响应失败! 状态码: ${response.status}`);
                }

                const reader = response.body.getReader();
                let responseContent = "";

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = new TextDecoder().decode(value);
                    const data = JSON.parse(chunk.substring(5));
                    const delta = data.choices[0].delta;
                    if (delta.content) {
                        responseContent += delta.content;
                        chatWindow.innerHTML += `<div class="message assistant">${delta.content}</div>`;
                    }
                }

                currentConversation.push({ role: "assistant", content: responseContent });
                chatHistory.push({ role: "assistant", content: responseContent });
            } catch (error) {
                console.error("请求发送失败:", error);
                alert(`请求发送失败: ${error.message}`);
            }

            userInput.value = "";
        }
    });

    // 初始化
    loadConversations();
});